package main

import (
	"os"
	"regexp"
	"strings"
)

// Struct to hold the extracted content
type ExtractedContent struct {
	YamlContent     string
	MarkdownContent string
}

// Function to extract YAML and Markdown content from a file
func extractContent(filename string) (ExtractedContent, error) {
	// Read the file content
	content, err := os.ReadFile(filename)
	if err != nil {
		return ExtractedContent{}, err
	}

	// Convert content to string
	contentStr := string(content)

	// Regular expressions to match YAML front matter and Markdown content
	yamlRegex := regexp.MustCompile(`(?s)^---\s*\n(.*?)\n---\s*\n`)
	markdownRegex := regexp.MustCompile(`(?s)^---\s*\n.*?\n---\s*\n(.*)`)

	// Extract YAML and Markdown content using the regular expressions
	yamlMatch := yamlRegex.FindStringSubmatch(contentStr)
	markdownMatch := markdownRegex.FindStringSubmatch(contentStr)

	// Handle cases where matches are not found
	yamlContent := ""
	markdownContent := contentStr
	if len(yamlMatch) > 1 {
		yamlContent = yamlMatch[1]
	}
	if len(markdownMatch) > 1 {
		markdownContent = markdownMatch[1]
	}

	// Return the extracted content
	return ExtractedContent{
		YamlContent:     yamlContent,
		MarkdownContent: markdownContent,
	}, nil
}

// Struct to hold the extracted Wiki link information
type WikiLink struct {
	Link        string
	Description string
}

// Function to extract Wiki links and tags from a file
func extractWikiLinksAndTags(content string) ([]WikiLink, []string, error) {

	// Regular expression to match Wiki links
	wikiLinkRegex := regexp.MustCompile(`\[\[([^|\]]+)(?:\|([^|\]]+))?\]\]`)
	// Regular expression to match tags regexp.MustCompile(`(^#(\w+)|[\s|\n]#(\w+))`)
	// regexp.MustCompile(`#(\w+)`)
	tagRegex := regexp.MustCompile(`(^#(\w+)\b|[\s|\n]#(\w+))\b`)

	// Find all Wiki link matches
	wikiLinkMatches := wikiLinkRegex.FindAllStringSubmatch(content, -1)
	// Find all tag matches
	tagMatches := tagRegex.FindAllStringSubmatch(content, -1)

	// Slice to hold the extracted Wiki links
	var wikiLinks []WikiLink
	// Slice to hold the extracted tags
	var tags []string

	// Process Wiki link matches
	for _, match := range wikiLinkMatches {
		link := match[1]
		description := match[1] // Default description to the link itself if not provided
		if len(match) > 2 && match[2] != "" {
			description = match[2]
		}
		wikiLinks = append(wikiLinks, WikiLink{Link: link, Description: description})
	}

	// Process tag matches
	for _, match := range tagMatches {
		// trimPrefix("#")
		tag := match[1]
		tag = strings.TrimSpace(tag)
		tag = strings.TrimPrefix(tag, "#")
		tags = append(tags, tag)
	}

	return wikiLinks, tags, nil
}
